package com.budwk.app.sqfwV2.generator.dayingRoadPdf;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.budwk.app.common.component.DictComponent;
import com.budwk.app.common.config.AppException;
import com.budwk.app.sqfw.models.Sqfw_formSummary_new;
import com.budwk.app.sqfwDoc.codeGenerator.pdfGenerate.AbstractCustomerPdfCreateField;
import com.budwk.app.sqfwDoc.codeGenerator.pdfGenerate.BaseTemplatePdfGenerator;
import com.budwk.app.sqfwDoc.codeGenerator.pdfGenerate.SqfwPdfCreateCommonBO;
import com.budwk.app.sqfwV2.component.DayingRoadPdfComponent;
import com.budwk.app.sqfwV2.dto.dto.FireSafetyOnDayingRoadPdfDTO;
import com.budwk.app.sqfwV2.dto.dto.centuryCity.SafeCheckTaskParamDataDTO;
import com.budwk.app.sqfwV2.enums.dayingRoad.KeySafetyIndustriesEnum;
import com.budwk.app.util.StrUtil;
import com.budwk.app.util.poiUtils.PictureUtils;
import com.budwk.starter.common.result.ResultCode;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.xwpf.NiceXWPFDocument;
import org.apache.commons.lang3.StringUtils;

import java.io.ByteArrayOutputStream;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 消防安全风险隐患排查整治台账，版本号1.0
 */
public class SafetyRiskStandingPdfGenerator extends BaseTemplatePdfGenerator{

    /**
    * 判断使用使用这个generator生成pdf
    *
    * @param pdfDTO 创建pdf数据素材
    * @return 结果
    */
    @Override
    public boolean pdfCreateConditionCheck(SqfwPdfCreateCommonBO pdfDTO) {
        AbstractCustomerPdfCreateField field = pdfDTO.getAbstractCustomerPdfCreateField();
        if (field == null) {
            throw new AppException(ResultCode.NULL_DATA_ERROR.getMsg());
        }
        if (field instanceof FireSafetyOnDayingRoadPdfDTO) {
            FireSafetyOnDayingRoadPdfDTO roadPdfDTO = (FireSafetyOnDayingRoadPdfDTO) field;
            String mainBusinessScope = roadPdfDTO.getMainBusinessScope();
            if (StringUtils.isEmpty(mainBusinessScope)) {
                return false;
            }
            // ○当【主要经营范围】的值为：【大型商场、超市、酒店】、【幼儿园、寄宿制学校、社会福利机构】、【医院、诊所、卫生服务站】、
            // 【劳动密集型企业、多业态混合经营场所】、【其他重点消防安全场所】中任意一项时，生成该表格。
            List<String> list = DictComponent.MAIN_BUSINESS_SCOPE_SAFETY_LIST();
            Optional<String> optional = list.stream().filter(code -> code.equals(mainBusinessScope)).findAny();
            if (optional.isPresent()) {
                return true;
            }
        }
        return false;
    }

    @Override
    public String getTemplateName() {
        return "sqfwV2/daYingLu/safetyRiskRecStandingBook.docx";
    }

    @Override
    public void customerPopularPdfParam(Map<String, Object> paramMap, SqfwPdfCreateCommonBO pdfDTO) {
        // 针对特殊字段进行数据填充 进行复杂的业务逻辑
        FireSafetyOnDayingRoadPdfDTO roadPdfDTO = DayingRoadPdfComponent.getFireSafetyOnDayingRoadPdfDTO(paramMap, pdfDTO);
        paramMap.put("district", DayingRoadPdfComponent.getDistrict(pdfDTO.getBasePdfParamDTO().getDistrict()));
        // 重点安全排查行业
        List<SafeCheckTaskParamDataDTO> keySafetyIndustries = roadPdfDTO.getKeySafetyIndustries();
        if (keySafetyIndustries == null || keySafetyIndustries.size() == 0) {
            keySafetyIndustries = KeySafetyIndustriesEnum.getAllDefaults();
        }
        for (SafeCheckTaskParamDataDTO keySafetyIndustry : keySafetyIndustries) {
            paramMap.put(keySafetyIndustry.getFields(), DayingRoadPdfComponent.getProblem(keySafetyIndustry));
        }
        // 隐患整改时限
        String inspectionDateStr = "无";
        LocalDateTime inspectionDate = roadPdfDTO.getInspectionDate();
        inspectionDate = inspectionDate == null ? LocalDateTime.now() : inspectionDate;
        if (roadPdfDTO.getRectificationDate() != null) {
            LocalDateTime ficationDateTime = roadPdfDTO.getRectificationDate().atTime(LocalTime.now());
            Duration between = LocalDateTimeUtil.between(inspectionDate, ficationDateTime);
            long days = between.toDays();
            if (days == 0) inspectionDateStr = "当天";
            else inspectionDateStr = days + "天";
        }
        paramMap.put("inspectionDateStr", inspectionDateStr);

        paramMap.put("otherHiddenDangers", "");
        List<SafeCheckTaskParamDataDTO> otherHiddenDangers = roadPdfDTO.getOtherHiddenDangers();
        if (otherHiddenDangers != null && otherHiddenDangers.size() > 0) {
            paramMap.put("otherHiddenDangers", otherHiddenDangers.get(otherHiddenDangers.size() - 1).getRectificationMeasure());
        }

        // 部门联合执法情况 (暂时不确定该参数  以前的a65)
        paramMap.put("departmentsJointSituation", StrUtil.formatStr(roadPdfDTO.getDeptJoinLawSituation()));
        // 当事人签名及协管员签字
        DayingRoadPdfComponent.buildPeersSign(pdfDTO, roadPdfDTO, paramMap);
    }

    @Override
    public ByteArrayOutputStream generatePDFAfter(XWPFTemplate xwpfTemplate, Sqfw_formSummary_new formSummary) {
        if (!DayingRoadPdfComponent.isDayYingStreet(formSummary.getUnitName())) {
            return null;
        }
        ByteArrayOutputStream wordOutPutStream = new ByteArrayOutputStream();
        if (xwpfTemplate != null) {
            NiceXWPFDocument xwpfDocument = xwpfTemplate.getXWPFDocument();
            try {
                xwpfDocument = PictureUtils.localImageSeal(xwpfDocument, "协管员签字", PictureUtils.getLocalImagePath(formSummary.getUnitName()),
                        65, -53, 115);
                xwpfDocument.write(wordOutPutStream);
                return wordOutPutStream;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                PictureUtils.close(xwpfTemplate, xwpfDocument);
            }
        }

        return wordOutPutStream;
    }
}
